<script setup>
import {computed, ref, watch} from "vue";

defineOptions({
  _tip_: '根据src计算referrerpolicy的图片封装，'
})
const {src} = defineProps({
  src: {
    type: String,
  },
})

const referrerpolicy = ref(null);
const srcNow = ref(null); // 当前组件使用的src ，需要做延时处理，避免src变化后，使用之前的 referrerpolicy 发起请求

function onChange(src){
  referrerpolicy.value = computeReferrerPolicy(src);
  srcNow.value = null;
  setTimeout(()=>{
    srcNow.value = src;
  },5)
}

function computeReferrerPolicy(src) {
  // no-referrer 模式加载图片的域名列表
  const noReferrerHostList = [
    /\/\/\w+\.qpic.cn\//, //微信公众号
  ];
  const noReferrer = noReferrerHostList.some((pattern) => {
    if (pattern instanceof RegExp) {
      return pattern.test(src);
    }
    if (typeof pattern === 'string') {
      return src.includes(`//${pattern}/`);
    }
    return false;
  });

  return noReferrer ? 'no-referrer' : null;
}

watch(() => src, (newSrc) => {
  onChange(newSrc)
}, { immediate: true });

onChange(src);
</script>

<template>
  <img :src="srcNow" :referrerpolicy="referrerpolicy"/>
</template>

<style scoped>

</style>